package com.bobby.shop.util;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;


import java.io.Serializable;

/**
 * @Description TODO
 * @Date 2020/7/10 12:23
 * @Created wenjunpei
 */

public class ServerResponse<T> implements Serializable {

    /**
     * 状态码
     */

    private  int status;

    /**
     * 响应信息
     */

    private  String msg;

    /**
     * 响应数据
     */

    private T data;

    /**
     * 构造函数
     *
     * @param status
     */
    private ServerResponse(int status) {
        this.status = status;
    }

    private ServerResponse(int status, String msg) {
        this.status = status;
        this.msg = msg;
    }

    private ServerResponse(int status, T data) {
        this.status = status;
        this.data = data;
    }

    private ServerResponse(int status, String msg, T data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    /**
     * 根据状态码返回是否成功
     * JsonIgnore使被注解内容不在json序列化结果当中
     *
     * @return
     */
    @JsonIgnore
    public boolean isSuccess() {
        return this.status == ResponseCode.SUCCESS.getCode();
    }

    /**
     * 暴露获取属性的方法
     *
     * @return
     */
    public  int getStatus() {
        return  this.status;
    }

    public  String getMsg() {
        return  this.msg;
    }

    public  T getData() {
        return  this.data;
    }

    /**
     * 通过该公开方法直接获取一个成功状态码的本对象
     *
     * @param <T>
     * @return
     */
    public static <T> ServerResponse<T> createBySuccess() {
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode());
    }

    public static <T> ServerResponse<T> createBySuccess(String msg) {
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(), msg);
    }

    public static <T> ServerResponse<T> createBySuccess(T data) {
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(), data);
    }

    public static <T> ServerResponse<T> createBySuccess(String msg, T data) {
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(), msg, data);
    }

    /**
     * 获取错误对象
     *
     * @param <T>
     * @return
     */
    public static <T> ServerResponse<T> createByError() {
        return new ServerResponse<T>(ResponseCode.ERROR.getCode(), ResponseCode.ERROR.getDesc());
    }

    public static <T> ServerResponse<T> createByError(String msg) {
        return new ServerResponse<T>(ResponseCode.ERROR.getCode(), msg);
    }

    public static <T> ServerResponse<T> createByError(ResponseCode responseCode) {
        return new ServerResponse<T>(responseCode.getCode(), responseCode.getDesc());
    }

}

